const formatNumber = (n) => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

export const formatTime = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
export const formatVoiceTime = (time) => {
  if (typeof time !== 'number' || time < 0) {
    return time
  }

  var hour = parseInt(time / 3600)
  time = time % 3600
  var minute = parseInt(time / 60)
  time = time % 60
  var second = time

  return ([hour, minute, second]).map(function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  }).join(':')
}
export function subStr(text, boolean = false) {
  const a = text.replace(/<br>/g, '\n');
  if (!boolean) {
    if (a.length > 200) {
      return `${a.substring(0, 200)}...`;
    }
  }
  return a;
}

function pluralize(time, label) {
  return time + label;
}

export function fromNow(time) {
  const between = Date.now() / 1000 - Number(time);
  if (between < 60) {
    return '刚刚';
  } else if (between < 3600) {
    return pluralize(~~(between / 60), '分钟前');
  } else if (between < 86400) {
    return pluralize(~~(between / 3600), '小时前');
  }
  return pluralize(~~(between / 86400), '天前');
}

export function formatDateTime(datetime) {
  const now = new Date();
  const year = now.getFullYear();
  if (Number(datetime.slice(0, 4)) !== year) {
    return datetime;
  }
  return datetime.slice(-14);
}
